package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.Course;
import com.eduadmin.service.ICourseService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CourseDataUploadListener extends AnalysisEventListener<Course> {
    private final ICourseService courseService;

    public CourseDataUploadListener(ICourseService courseService) {
        this.courseService = courseService;
    }

    private static final int BATCH_COUNT = 600;
    List<Course> list = new ArrayList<>();

    @Override
    public void invoke(Course data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        Course course = courseService.getCourseByCourseName(data.getCourseChName());
        if (course == null) {
            list.add(data);
        }
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            courseService.addCourses(list);
        }
        log.info("存储数据库成功！");
    }


}
